#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import pandas as pd
import logging
import sys
import json
import conf.config_default as conf
logging.basicConfig(level=logging.INFO)


def loadData(stock_code,index_code,start_date,end_date):
    """
    :param stock_code: 股票代码，例如‘000001.SZ’
    :param index_code: 指数代码，例如‘sh000001’
    :param start_date: 回测开始日期，例如‘1991-1-30'
    :param end_date: 回测结束日期，例如‘2015-12-31’
    :return: 函数返回其他函数的各参数序列
    """
    logging.info('loading data start')
    DataPath=conf.configs['filedb']['StockPath']
    logging.info("read path is %s,current filepath is %s" % (DataPath,__file__))
    stock_name = stock_code+".xls"; index_name=index_code+".xls"
    stock_path = os.path.abspath(os.path.join(os.path.abspath(DataPath),stock_name))
    index_path=os.path.abspath(os.path.join(os.path.abspath(DataPath),index_name))

    logging.info('the target data file path is %s ;index data path is %s' % (stock_path,index_path))

    try:
        df_stock = pd.read_excel(stock_path, sheet_name=stock_code)
        df_stock['date'] = pd.to_datetime(df_stock['日期'])
        df_stock.set_index('date', inplace=True)
        df_stock.loc[df_stock['涨跌幅(%)'] == '--', '涨跌幅(%)'] = "0.00"
        df_stock['rtn'] = df_stock['涨跌幅(%)'].astype(float);
        df_stock['close'] = df_stock['收盘价(元)'].astype(float);
        df_stock.sort_index(ascending=True, inplace=True)
        df_stock=df_stock[start_date:end_date]

        df_index=pd.read_excel(index_path, sheet_name=index_code)
        df_index['date'] = pd.to_datetime(df_index['日期'])
        df_index.set_index('date', inplace=True)
        df_index.loc[df_index['涨跌幅(%)'] == '--', '涨跌幅(%)'] = "0.00"
        df_index['rtn'] = df_index['涨跌幅(%)'].astype(float);
        df_index['close'] = df_index['收盘价'].astype(float);
        df_index.sort_index(ascending=True, inplace=True)
        df_index=df_index[start_date:end_date]

        date_line = df_stock.index
        capital_line = df_stock['close']
        return_line = df_stock['rtn'] / 100
        index_line = df_index['close']
        indexreturn_line = df_index['rtn'] / 100
        logging.info("loading data success")

        return {
                 'date_line':date_line,
                 'capital_line':capital_line,
                 'return_line':return_line,
                 'index_line':index_line,
                 'indexreturn_line':indexreturn_line
                }
    except FileNotFoundError as e:
        logging.error('cant read excel file%s' % e)

def query( code, index,start, end ):
    logging.info("the stockDAO query begins.....")
    data_set = loadData(code, index,start, end)
    logging.info("the stockDAO query ends.....")
    return data_set

if __name__ == '__main__':
    query("000001.SZ","hs300","2018-02-20","2018-03-13")

